package com.woniuxy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * User类实现UserDetails接口，CustomUserDetailService的返回值就成为了UserDetails
 * */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable, UserDetails {

    private int id;
    private String account;
    private String password;
    private String avatar;
    private String telphone;
    private String email;
    private String registdate;  // 注册时间
    private String lastlogin;
    private String state;
    private List<Role> roles;       // 一个用户多个角色


    /**
     * getAuthorities: 获取当前用户的所有角色和权限  【重要】
     * getUsername：获得用户的账号
     * isAccountNonExpired：判断账号是否过期   true  没过期
     * isAccountNonLocked：判断账号是否被锁定   true 未锁定
     * isCredentialsNonExpired：判断密码是否过期   false 凭证过期
     * isEnabled：判断账号是否禁用  true  账号未被禁用
     * */

    // TODO 封装角色和权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 遍历所有的角色
        for (Role role: this.roles){
            // 封装角色信息
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            // 封装权限信息
            for (Perms perms:role.getPerms()){
                authorities.add(new SimpleGrantedAuthority(perms.getName()));
            }
        }
        return authorities;
    }

    /**
     * 将下列的返回值都改为true，否则页面会报账户被锁定的错
     * */
    @Override
    public String getUsername() {
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
